#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>

#define NN 64

void* RecvData(void* arg)
{
    int* c_socket=(int*)arg;
    int client_socket=*c_socket;
    free(c_socket);
    while (1)
    {

        char buf[NN]={0};
        int ret =0;
        ret=recv(client_socket,buf,NN,0);
        if(ret<0)
        {
            perror("recv err\n");
            break;
            // close(client_socket);
            // pthread_exit(0);
        }
        else if(ret>0)
        {
            printf("%s\n",buf);
            send(client_socket,"recv success",64,0);
        }
        else
        {
            printf("peer quit\n");
            break;
            // close(client_socket);
            // pthread_exit(0);
        }
    }
    close(client_socket);
    return NULL;
}

// 用法：./server 8888
int main(int argc, char const* argv[])
{
    int server_socket;
    server_socket = socket(AF_INET,SOCK_STREAM,0);
    if (server_socket==-1)
    {
        perror("socket err\n");
        return -1;
    }
    
    struct sockaddr_in addr;
    addr.sin_family=AF_INET;
    addr.sin_port=htons(8888);
    addr.sin_addr.s_addr=INADDR_ANY;

    if(bind(server_socket,(struct sockaddr*)&addr,sizeof(addr))==-1)
    {
        perror("bind err\n");
        return -1;
    }

         if (listen(server_socket,5)==-1)
        {
            perror("listen err\n");
            return -1;
        }
        printf("等待接收\n");

        // int client_socket=-1;
        struct sockaddr_in client_addr;
        socklen_t client_addr_len = sizeof(client_addr);        
        while (1)
        {
            int client_socket=-1;
            client_socket=accept(server_socket,(struct sockaddr*)&client_addr,&client_addr_len);

            printf("ip = %s\n",inet_ntoa(client_addr.sin_addr));

            if (client_socket==-1)
            {
                perror("accept err\n");
                return -1;
            }
            pthread_t thread;
            int *c_socket=(int*)malloc(sizeof(int));
            *c_socket=client_socket;
            if(pthread_create(&thread,NULL,RecvData,(void*)c_socket) != 0)
            {
                perror("create thread error");
                return -1;
            }
            pthread_detach(thread);
        }
       //有高并发要求，系统需要很快的响应速度
       //一般情况把线程提前做，做一个线程池
       //没有频繁创建线程，减少线程创建的开销
       //启动慢，但启动之后快
       //更容易管理 
        
    close(server_socket);
    while (1);
    
    return 0;
}